package com.hxgis.statisticanalysis.utils;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;

import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;

@Component
public class DataPathCom {

    @Value("${work.dir:}")
    private String dataRootPath;

    private static final String defaultSubDir = "/data/";

    /**
     * 获取数据文件保存的根路径
     * @return string
     */
    public String getRootPath() {
        String path = "";
        try {
            if (StringUtils.isNotBlank(dataRootPath)) {
                path = dataRootPath;
            } else {
                File folder = new File(ResourceUtils
                        .getURL(ResourceUtils.CLASSPATH_URL_PREFIX)
                        .toURI()
                        .getPath());
                File subFolder = new File(folder.getCanonicalPath());
                if (!subFolder.exists()) {
                    subFolder.mkdir();
                }
                path = subFolder.getCanonicalPath();
            }
        } catch (URISyntaxException | IOException e) {
            e.printStackTrace();
        }
        if (!path.endsWith(File.separator)) {
            path += File.separator;
        }
        path += "data" + File.separator;
        return path;
    }

    /**
     * 获取数据文件保存的根路径
     * @return string
     */
    public String getRelativeRootPath() {
        String path = "";
        try {
            File folder = new File(ResourceUtils
                    .getURL(ResourceUtils.CLASSPATH_URL_PREFIX)
                    .toURI()
                    .getPath());
            File subFolder = new File(folder.getCanonicalPath());
            if (!subFolder.exists()) {
                subFolder.mkdir();
            }
            path = subFolder.getCanonicalPath();
        } catch (URISyntaxException | IOException e) {
            e.printStackTrace();
        }
        if (!path.endsWith(File.separator)) {
            path += File.separator;
        }
        path += "data" + File.separator;
        return path;
    }
}
